package dao

import (
	"lib/id"
	"lib/structs/tables"
	"sys/global"
	"time"
)

var RoleDB = new(roleRepository)

type roleRepository struct{}

func (d roleRepository) SelectRolesByUserId(userId int64) (li []tables.Role, err error) {
	err = global.DB.Raw("select * from sys_role where role_id in ( "+
		" select role_id from sys_map_user_role where user_id =? )", userId).Scan(&li).Error
	return
}

func (d roleRepository) FindAll(isOpen int) (li []tables.Role, err error) {
	err = global.DB.Where("is_open =?", isOpen).Find(&li).Error
	return
}

func (d roleRepository) Create(m tables.Role) (err error) {
	m.RoleId = id.GetSnowId()
	m.CreatedAt = time.Now().Unix()
	err = global.DB.Create(&m).Error
	return
}

func (d roleRepository) DeleteById(id int64) (err error) {
	err = global.DB.Model(&tables.Role{}).Delete(&tables.Role{RoleId: id}).Where(&tables.Role{RoleId: id}).Error
	return err
}
